{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "google",
   "metadata": {},
   "source": [
    "##### Copyright 2023 Google LLC."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "apache",
   "metadata": {},
   "source": [
    "Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "you may not use this file except in compliance with the License.\n",
    "You may obtain a copy of the License at\n",
    "\n",
    "    http://www.apache.org/licenses/LICENSE-2.0\n",
    "\n",
    "Unless required by applicable law or agreed to in writing, software\n",
    "distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "See the License for the specific language governing permissions and\n",
    "limitations under the License.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "basename",
   "metadata": {},
   "source": [
    "# minesweeper"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "link",
   "metadata": {},
   "source": [
    "<table align=\"left\">\n",
    "<td>\n",
    "<a href=\"https://colab.research.google.com/github/google/or-tools/blob/main/examples/notebook/contrib/minesweeper.ipynb\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/colab_32px.png\"/>Run in Google Colab</a>\n",
    "</td>\n",
    "<td>\n",
    "<a href=\"https://github.com/google/or-tools/blob/main/examples/contrib/minesweeper.py\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/github_32px.png\"/>View source on GitHub</a>\n",
    "</td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "doc",
   "metadata": {},
   "source": [
    "First, you must install [ortools](https://pypi.org/project/ortools/) package in this colab."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "install",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install ortools"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "description",
   "metadata": {},
   "source": [
    "\n",
    "\n",
    "  Minesweeper in Google CP Solver.\n",
    "\n",
    "  From gecode/examples/minesweeper.cc:\n",
    "  '''\n",
    "  A specification is a square matrix of characters. Alphanumeric\n",
    "  characters represent the number of mines adjacent to that field.\n",
    "  Dots represent fields with an unknown number of mines adjacent to\n",
    "  it (or an actual mine).\n",
    "  '''\n",
    "\n",
    "  E.g.\n",
    "       '..2.3.'\n",
    "       '2.....'\n",
    "       '..24.3'\n",
    "       '1.34..'\n",
    "       '.....3'\n",
    "       '.3.3..'\n",
    "\n",
    "\n",
    "  Also see:\n",
    "  * http://www.janko.at/Raetsel/Minesweeper/index.htm\n",
    "\n",
    "  * http://en.wikipedia.org/wiki/Minesweeper_(computer_game)\n",
    "\n",
    "  * Ian Stewart on Minesweeper:\n",
    "    http://www.claymath.org/Popular_Lectures/Minesweeper/\n",
    "\n",
    "  * Richard Kaye's Minesweeper Pages\n",
    "    http://web.mat.bham.ac.uk/R.W.Kaye/minesw/minesw.htm\n",
    "\n",
    "  * Some Minesweeper Configurations\n",
    "    http://web.mat.bham.ac.uk/R.W.Kaye/minesw/minesw.pdf\n",
    "\n",
    "\n",
    "  Compare with the following models:\n",
    "  * MiniZinc: http://www.hakank.org/minizinc/minesweeper.mzn\n",
    "  * Choco   : http://www.hakank.org/choco/MineSweeper.java\n",
    "  * JaCoP   : http://www.hakank.org/JaCoP/MineSweeper.java\n",
    "  * Gecode/R: http://www.hakank.org/gecode_r/minesweeper.rb\n",
    "  * Comet   : http://www.hakank.org/comet/minesweeper.co\n",
    "  * ECLiPSe : http://www.hakank.org/eclipse/minesweeper.ecl\n",
    "  * SICStus : http://www.hakank.org/sicstus/minesweeper.pl\n",
    "  * Tailor/Essence': http://www.hakank.org/tailor/minesweeper.eprime\n",
    "  * Zinc: http://www.hakank.org/minizinc/minesweeper.zinc\n",
    "\n",
    "  This model was created by Hakan Kjellerstrand (hakank@gmail.com)\n",
    "  Also see my other Google CP Solver models:\n",
    "  http://www.hakank.org/google_or_tools/\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "code",
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "from ortools.constraint_solver import pywrapcp\n",
    "\n",
    "default_r = 8\n",
    "default_c = 8\n",
    "X = -1\n",
    "default_game = [[2, 3, X, 2, 2, X, 2, 1], [X, X, 4, X, X, 4, X, 2],\n",
    "                [X, X, X, X, X, X, 4, X], [X, 5, X, 6, X, X, X, 2],\n",
    "                [2, X, X, X, 5, 5, X, 2], [1, 3, 4, X, X, X, 4, X],\n",
    "                [0, 1, X, 4, X, X, X, 3], [0, 1, 2, X, 2, 3, X, 2]]\n",
    "\n",
    "\n",
    "def main(game=\"\", r=\"\", c=\"\"):\n",
    "\n",
    "  # Create the solver.\n",
    "  solver = pywrapcp.Solver(\"Minesweeper\")\n",
    "\n",
    "  #\n",
    "  # data\n",
    "  #\n",
    "\n",
    "  # Set default problem\n",
    "  if game == \"\":\n",
    "    game = default_game\n",
    "    r = default_r\n",
    "    c = default_c\n",
    "  else:\n",
    "    print(\"rows:\", r, \" cols:\", c)\n",
    "\n",
    "  #\n",
    "  # Default problem from \"Some Minesweeper Configurations\",page 3\n",
    "  # (same as problem instance minesweeper_config3.txt)\n",
    "  # It has 4 solutions\n",
    "  #\n",
    "  # r = 8\n",
    "  # c = 8\n",
    "  # X = -1\n",
    "  # game = [\n",
    "  #     [2,3,X,2,2,X,2,1],\n",
    "  #     [X,X,4,X,X,4,X,2],\n",
    "  #     [X,X,X,X,X,X,4,X],\n",
    "  #     [X,5,X,6,X,X,X,2],\n",
    "  #     [2,X,X,X,5,5,X,2],\n",
    "  #     [1,3,4,X,X,X,4,X],\n",
    "  #     [0,1,X,4,X,X,X,3],\n",
    "  #     [0,1,2,X,2,3,X,2]\n",
    "  #     ]\n",
    "\n",
    "  S = [-1, 0, 1]  # for the neighbors of \"this\" cell\n",
    "\n",
    "  # print problem instance\n",
    "  print(\"Problem:\")\n",
    "  for i in range(r):\n",
    "    for j in range(c):\n",
    "      if game[i][j] == X:\n",
    "        print(\"X\", end=\" \")\n",
    "      else:\n",
    "        print(game[i][j], end=\" \")\n",
    "    print()\n",
    "  print()\n",
    "\n",
    "  # declare variables\n",
    "  mines = {}\n",
    "  for i in range(r):\n",
    "    for j in range(c):\n",
    "      mines[(i, j)] = solver.IntVar(0, 1, \"mines %i %i\" % (i, j))\n",
    "\n",
    "  #\n",
    "  # constraints\n",
    "  #\n",
    "  for i in range(r):\n",
    "    for j in range(c):\n",
    "      if game[i][j] >= 0:\n",
    "        solver.Add(mines[i, j] == 0)\n",
    "        # this cell is the sum of all the surrounding cells\n",
    "        solver.Add(game[i][j] == solver.Sum([\n",
    "            mines[i + a, j + b]\n",
    "            for a in S\n",
    "            for b in S\n",
    "            if i + a >= 0 and j + b >= 0 and i + a < r and j + b < c\n",
    "        ]))\n",
    "      if game[i][j] > X:\n",
    "        # This cell cannot be a mine\n",
    "        solver.Add(mines[i, j] == 0)\n",
    "\n",
    "  #\n",
    "  # solution and search\n",
    "  #\n",
    "  solution = solver.Assignment()\n",
    "  solution.Add([mines[(i, j)] for i in range(r) for j in range(c)])\n",
    "\n",
    "  collector = solver.AllSolutionCollector(solution)\n",
    "  solver.Solve(\n",
    "      solver.Phase([mines[(i, j)] for i in range(r) for j in range(c)],\n",
    "                   solver.INT_VAR_SIMPLE, solver.ASSIGN_MIN_VALUE), [collector])\n",
    "\n",
    "  num_solutions = collector.SolutionCount()\n",
    "  print(\"num_solutions: \", num_solutions)\n",
    "  if num_solutions > 0:\n",
    "    for s in range(num_solutions):\n",
    "      minesval = [\n",
    "          collector.Value(s, mines[(i, j)]) for i in range(r) for j in range(c)\n",
    "      ]\n",
    "      for i in range(r):\n",
    "        for j in range(c):\n",
    "          print(minesval[i * c + j], end=\" \")\n",
    "        print()\n",
    "      print()\n",
    "\n",
    "    print()\n",
    "    print(\"num_solutions:\", num_solutions)\n",
    "    print(\"failures:\", solver.Failures())\n",
    "    print(\"branches:\", solver.Branches())\n",
    "    print(\"WallTime:\", solver.WallTime())\n",
    "\n",
    "  else:\n",
    "    print(\"No solutions found\")\n",
    "\n",
    "\n",
    "#\n",
    "# Read a problem instance from a file\n",
    "#\n",
    "def read_problem(file):\n",
    "  f = open(file, \"r\")\n",
    "  rows = int(f.readline())\n",
    "  cols = int(f.readline())\n",
    "  game = []\n",
    "  for i in range(rows):\n",
    "    x = f.readline()\n",
    "    row = [0] * cols\n",
    "    for j in range(cols):\n",
    "      if x[j] == \".\":\n",
    "        tmp = -1\n",
    "      else:\n",
    "        tmp = int(x[j])\n",
    "      row[j] = tmp\n",
    "    game.append(row)\n",
    "  return [game, rows, cols]\n",
    "\n",
    "\n",
    "#\n",
    "# Print the mines\n",
    "#\n",
    "def print_mines(mines, rows, cols):\n",
    "  for i in range(rows):\n",
    "    for j in range(cols):\n",
    "      print(mines[i, j], end=\" \")\n",
    "    print(\"\")\n",
    "\n",
    "\n",
    "def print_game(game, rows, cols):\n",
    "  for i in range(rows):\n",
    "    for j in range(cols):\n",
    "      print(game[i][j], end=\" \")\n",
    "    print(\"\")\n",
    "\n",
    "\n",
    "if len(sys.argv) > 1:\n",
    "  file = sys.argv[1]\n",
    "  print(\"Problem instance from\", file)\n",
    "  [game, rows, cols] = read_problem(file)\n",
    "  # print_game(game, rows, cols)\n",
    "  main(game, rows, cols)\n",
    "else:\n",
    "  main()\n",
    "\n"
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 5
}
